<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%--
  Created by IntelliJ IDEA.
  User: qupen
  Date: 2016/11/3
  Time: 15:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:include page="../include/head.jsp">
    <jsp:param name="title" value="监控仪表板"/>
</jsp:include>

<jsp:include page="../include/tenant_header.jsp"/>

<jsp:include page="../include/tenant_sidebar.jsp"/>
<div class="content-wrapper content-wrapper-bg">
    <section class="content-header">
        <h4 class="page-title" style="display: inline-block">监控仪表板</h4>
    </section>
    <input type="text" class="hidden" id="deviceId" value="${device.device_id}" >
    <input type="text" class="hidden" id="deviceName" value="${device.device_unique_id}">
    <%--机床信息--%>
    <section class="content" style="min-height: 0;">
        <div class="dashboard-mt-info">
            <div class="dashboard-info-img">
                <img src="/api/v1/image/get?name=${device.device_img}">
            </div><!--
            --><div class="dashboard-info-border">
                <div style="width:100%;display: inline-block;">
                    <scan class="dashboard-info-name">
                        <spring:message code="label.device.id"/>:
                    </scan>
                    <c:choose>
                        <c:when test="${device.device_unique_id == null}">
                            <i class="dashboard-info-detail"><spring:message code="label.without"/></i>
                        </c:when>
                        <c:otherwise>
                            <i class="dashboard-info-detail">${device.device_unique_id}</i>
                        </c:otherwise>
                    </c:choose>
                </div>
                <div style="width:100%;display: inline-block;margin: 5px 0;">
                    <scan class="dashboard-info-name">
                        <spring:message code="label.current.state"/>:
                    </scan>
                    <i class="dashboard-info-detail">${device.state}</i>
                </div>
            </div><!--
            --><div class="dashboard-info-border">
                <div style="width:100%;display: inline-block;">
                    <scan class="dashboard-info-name">
                        <spring:message code="label.group"/>:
                    </scan>
                    <c:choose>
                        <c:when test="${device.group == null}">
                            <i class="dashboard-info-detail"><spring:message code="label.without"/></i>
                        </c:when>
                        <c:otherwise>
                            <i class="dashboard-info-detail">${device.group}</i>
                        </c:otherwise>
                    </c:choose>
                </div>
                <div style="width:100%;display: inline-block;margin: 5px 0;">
                    <scan class="dashboard-info-name">
                        <spring:message code="label.operator"/>:
                    </scan>
                    <i class="dashboard-info-detail">${loginUser.userName}</i>
                </div>
            </div><!--
            --><div class="dashboard-info-border">
                <div style="width:100%;display: inline-block;">
                    <scan class="dashboard-info-name">
                        <spring:message code="label.device.line"/>:
                    </scan>
                    <c:choose>
                        <c:when test="${device.line == null}">
                            <i class="dashboard-info-detail"><spring:message code="label.without"/></i>
                        </c:when>
                        <c:otherwise>
                            <i class="dashboard-info-detail">${device.line}</i>
                        </c:otherwise>
                    </c:choose>
                </div>
                <%--<div style="width:100%;display: inline-block;margin: 5px 0;">--%>
                    <%--<scan class="dashboard-info-name">--%>
                        <%--PC Station:--%>
                    <%--</scan>--%>
                    <%--<i style="line-height: 1;color: #666666">AAECNWUX</i>--%>
                <%--</div>--%>
            </div><!--
             --><div class="dashboard-info-border">
                <div class="sie-calendar-parent">
                    <input type="text" readonly="readonly" class="form-control sie-calendar-input" id="hoursTimeLine">
                    <img src="/images/calendar.png" class="sie-calendar-img">
                </div>
            </div>
        </div>
    </section>
    <div class="content-header row" style="color: #fff">
        <div class="col-md-3" style="padding: 0;">
            <div id="recently_oee" class="dashboard-service-show">
                <scan class="dashboard-service-scan">
                    OEE
                </scan>
                <i class="dashboard-service-i"></i>
            </div>
        </div>
        <div class="col-md-3" style="padding: 0;">
            <div id="recently_availability" class="dashboard-service-show">
                <scan class="dashboard-service-scan">
                    Availability
                </scan>
                <i class="dashboard-service-i"></i>
            </div>
        </div>
        <div class="col-md-3" style="padding: 0;">
            <div id="recently_performance" class="dashboard-service-show">
                <scan class="dashboard-service-scan">
                    Performance
                </scan>
                <i class="dashboard-service-i"></i>
            </div>
        </div>
        <div class="col-md-3" style="padding: 0;">
            <div id="recently_quality" class="dashboard-service-show">
                <scan class="dashboard-service-scan">
                    Quality
                </scan>
                <i class="dashboard-service-i"></i>
            </div>
        </div>
    </div>
    <%--24小时时间线--%>
    <div class="content-header">
        <div class="dashboard-chart-border">
            <div class="mybtn">
                <a data-id="mac" id="mac-select" onclick="changePage(this)" class="default selector" href="javascript:;">
                    <span>Machine Information</span>
                </a>
                <a data-id="dot" id="dot-select" onclick="changePage(this)" class="default" href="javascript:;">
                    <span>Downtime Record</span>
                </a>
            </div>
            <div id="mac-table">
                <div class="dashboard-chart-title">
                    <p class="dashboard-chart-name">24小时状态时间线</p>
                </div>
                <div style="padding: 20px;">
                    <div class="dashboard-chart-line">
                        <div class="dashboard-hours-hint">
                            <div class="hours-hint-point" style="background-color: #aaaa96"></div>
                            <span>WORK</span>

                            <div class="hours-hint-point" style="background-color:#d7d7d7;"></div>
                            <span>IDLE</span>

                            <div class="hours-hint-point" style="background-color:#73645a;"></div>
                            <span>Power OFF</span>
                        </div>
                        <div class="static-line-border">
                            <div id="timeLine" style="height: 40px;"></div>
                            <div style="position: static;">
                                <c:forEach begin="1" end="24" step="1" varStatus="status">
                                    <c:if test="${status.index<10||status.index==10}">
                                        <div style="width:4.1666%;float:left;">0${status.index-1}</div>
                                    </c:if>
                                    <c:if test="${status.index>10}">
                                        <div style="width:4.1666%;float:left;">${status.index-1}</div>
                                    </c:if>
                                </c:forEach>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<jsp:include page="../include/foot.jsp"/>
<script src="/js/dx.all.js"></script>
<script src="/js/charts.js"></script>
<script>
    var mttr= 0,mtbr=0;
    $(function () {
        //初始化24小时时间插件 并加入时间改变需要进行的操作
        $("#hoursTimeLine").datepicker({
            language: "zh-CN",
            autoclose: true,
            format: "yyyy-mm-dd",
            endDate: dateFormat(new Date()),
            todayHighlight:true
        }).on('changeDate', function (ev) {
            $("#mac").empty();
            $("dot").empty();
            recentlyIndexParam();
            if($("#mac-select").hasClass("selector")){
                loadMacPage();
            }else if($("#dot-select").hasClass("selector")){
                loadDotPage();
            }
        });

        //默认
        $("#hoursTimeLine").val(dateFormat(dateAddSubtract(new Date(), -1)));
        $("#hoursTimeLine").datepicker("update");

        bindDateInputClickEvent();//bind date img click
    });

    function recentlyIndexParam() {
        $.ajax({
            url: "/partner/{tenant}/api/v1/recentlyIndexParam".replace("{tenant}", getKeyByUrl()),
            data: {
                "deviceId": $("#deviceId").val(),
                "day": $("#hoursTimeLine").val()
            },
            type: "get",
            success: function (data) {
                if (data.result != 'SUCCESS' || Object.keys(data.data).length == 0) {
                    $("#recently_oee").find("i").text('<spring:message code="label.without.data"/>');
                    $("#recently_availability").find("i").text('<spring:message code="label.without.data"/>');
                    $("#recently_performance").find("i").text('<spring:message code="label.without.data"/>');
                    $("#recently_quality").find("i").text('<spring:message code="label.without.data"/>');
                    return;
                }
                if (data.data.oee == null) {
                    $("#recently_oee").find("i").text('<spring:message code="label.without.data"/>');
                } else {
                    $("#recently_oee").find("i").text((data.data.oee * 100).toFixed(2) + "%");
                }
                if (data.data.availability == null) {
                    $("#recently_availability").find("i").text('<spring:message code="label.without.data"/>');
                } else {
                    $("#recently_availability").find("i").text((data.data.availability * 100).toFixed(2) + "%");
                }
                if (data.data.performance == null) {
                    $("#recently_performance").find("i").text('<spring:message code="label.without.data"/>');
                } else {
                    $("#recently_performance").find("i").text((data.data.performance * 100).toFixed(2) + "%");
                }
                if (data.data.quality == null) {
                    $("#recently_quality").find("i").text('<spring:message code="label.without.data"/>');
                } else {
                    $("#recently_quality").find("i").text((data.data.quality * 100).toFixed(2) + "%");
                }
            },
            error: function (e) {
                console.log(e);
            }
        })
    }

    function loadMacPage(){
        var $chart_one =
                $("<div></div>").addClass("chart dashboard-chart-div").attr('id', 'mac').append(
                        $("<div></div>").attr("style", "min-height:0;").append(
                                $("<div></div>").addClass('dashboard-chart-title').append(
                                        $("<p></p>").addClass("dashboard-chart-name").text("OEE 近期趋势"))).append(
                                $("<div></div>").addClass('col-md-12').attr("style", 'padding: 20px;').append(
                                        $("<div></div>").addClass("chart-line-width").append(
                                                $("<div></div>").addClass("chartContainer hidden chart-service-choose").append(
                                                        $("<div></div>").attr({id:"indexparam",style:"width: 100%;height: 30px;color:#000"}).append(
                                                                $("<div></div>").addClass("radio selected").attr("data-name",'oee').text("OEE")).append(
                                                                $("<div></div>").addClass("radio").attr("data-name",'availability').text("AVAILABILITY")).append(
                                                                $("<div></div>").addClass("radio").attr("data-name",'quality').text("QUALITY")).append(
                                                                $("<div></div>").addClass("radio").attr("data-name",'performance').text("PERFORMANCE")))).append(
                                                $("<div></div>").attr("style","padding:20px;").append(
                                                        $("<div></div>").attr("style","font-size:18px;color: #575757;margin-bottom:10px;text-align:center;").text('<spring:message code="label.chart.period.oee"/>')
                                                ).append(
                                                        $("<div></div>").attr({"id": "serviceLine"}).addClass("dx-visibility-change-handler")
                                                )))).append(
                                $("<div></div>").addClass("row chart-line-row").append(
                                        $("<div></div>").addClass("col-md-6").attr("style", "padding-left: 0;").append(
                                                $("<div></div>").addClass("chart-line-width").attr("style","padding:20px;").append(
                                                        $("<div></div>").attr("style","text-align: center;font-size: 18px;color: #575757;").text('<spring:message code="label.chart.pie.day.device.state"/>')
                                                ).append(
                                                        $("<div></div>").attr({id: "workStatePieChart"}).addClass("dx-visibility-change-handler")))).append(
                                        $("<div></div>").addClass("col-md-6").attr("style", "padding-left: 0;").append(
                                                $("<div></div>").addClass("chart-line-width").attr("style","padding:20px;").append(
                                                        $("<div></div>").attr("style","text-align: center;font-size: 18px;color: #575757;").text('<spring:message code="label.chart.bar.day.idle"/>')
                                                ).append(
                                                        $("<div></div>").attr({id: "idleReasonBarChart"}).addClass("dx-visibility-change-handler"))
                                        )
                                )
                        )
                );

        $("#mac-table").after($chart_one);
        twentyFourHoursLine($("#deviceId").val());
        //获取数据oee显示
        indexServicesLineChart();
        //获取distribution of working status
        workStatusPie();
        //获取数据：某天idle原因的分布
        getDayIdleReason();
    }

    function loadDotPage(){
        var staticLine= $("<div></div>").attr("style",'position: static;');
        for (var i =0;i<24;i++){
            console.log(i);
            staticLine.append($("<div></div>").attr("style","width:4.1666%;float:left;").text(i<9||i==9?"0"+i:i));
        }

        var $chart_tow = $("<div></div>").addClass("chart dashboard-chart-div").attr('id', 'mac').append(
                $("<div></div>").attr("style", "min-height:0;").append(
                        $("<div></div>").addClass('dashboard-chart-title').append(
                                $("<p></p>").addClass("dashboard-chart-name").text("维修状态时间线"))).append(
                        $("<div></div>").attr("style", 'padding: 20px;').append(
                                $("<div></div>").addClass('dashboard-chart-line').attr("style","height:102px;").append(
                                        $("<div></div>").addClass("static-line-border").attr({id:"failureLine",style:'height: 40px;'})).append(
                                        staticLine)).append(
                                $("<div></div>").addClass("chart-table-border").append(
                                        $("<table></table>").addClass("table").attr("id","downTimeTable").append(
                                                $("<thead></thead>").append(
                                                        $("<tr></tr>").append(
                                                                $('<th></th>').text('<spring:message code="label.start.time"/>')).append(
                                                                $('<th></th>').text('<spring:message code="label.end.time"/>')).append(
                                                                $('<th></th>').text('<spring:message code="label.tenant.fault.model"/>')).append(
                                                                $('<th></th>').text('<spring:message code="label.reason"/>')).append(
                                                                $('<th></th>').text('<spring:message code="label.tenant.repair.personnel"/>')))))).append(
                                $("<div></div>").addClass("row chart-line-row").attr("style",'margin:0').append(
                                        $("<div></div>").addClass("col-md-6").attr("style","padding-left:0;").append(
                                                $("<div></div>").addClass("chart-line-width").attr("style","padding:20px;").append(
                                                        $("<div></div>").attr("style","text-align: center;font-size: 18px;color: #575757;").text('<spring:message code="label.chart.pie.downtime.record"/>')
                                                ).append(
                                                        $("<div></div>").addClass("dx-visibility-change-handler").attr("id","mttrBarChart")))).append(
                                        $("<div></div>").addClass("col-md-6").attr("style","padding-left:0;").append(
                                                $("<div></div>").addClass("chart-line-width").attr("style","padding:20px;").append(
                                                        $("<div></div>").attr("style","text-align: center;font-size: 18px;color: #575757;").text('<spring:message code="label.chart.bar.downtime.record"/>')
                                                ).append(
                                                        $("<div></div>").addClass("dx-visibility-change-handler").attr("id","mtbrBarChart"))
                                        )
                                )
                        )
                )
        );

        $("#mac-table").after($chart_tow);

        twentyFourHoursLine($("#deviceId").val());
        failureTimeLine();
        //other
        pieChartOfDownTimeWeek();
        barChartOfDownTimeWeek();
        getDownTimeTable();
    }

    function workStatusPie() {
        var data = {
            day: $("#hoursTimeLine").val(),
            deviceId: $("#deviceId").val()
        };
        var url;
        if($('#hoursTimeLine').val() != dateFormat(new Date())){
            url = "/partner/{tenant}/api/v1/workStatusPie".replace("{tenant}", getKeyByUrl());
        }else{
            url = "/partner/{tenant}/api/v1/workStatusPieByCalculate".replace("{tenant}", getKeyByUrl());
        }
        $.ajax({
            url: url,
            data: data,
            get: 'get',
            success: function (data) {
                if (data.result != 'SUCCESS' || data.data.length == 0) {
                    createDayWorkStatePieChart([]);
                }
                createDayWorkStatePieChart(data.data);
            },
            error: function (e) {
                console.log(e);
            }
        })
    }

    function getDayIdleReason() {
        var data = {
            day: $("#hoursTimeLine").val(),
            deviceId: $("#deviceId").val()
        };
        $.ajax({
            url: "/partner/{tenant}/api/v1/getDayIdleReason".replace("{tenant}", getKeyByUrl()),
            data: data,
            type: 'get',
            success: function (data) {
                if (data.result != 'SUCCESS' || data.data.length == 0) {
                    createDayIdleReasonBarChart([]);
                }
                console.log(data.data);
                createDayIdleReasonBarChart(data.data);
            },
            error: function (e) {
                console.log(e);
            }
        })
    }

    //获取数据：一段时间 oee或performance或quality或availability indexParam趋势
    function indexServicesLineChart(dom, prefix) {
        var data = {};
        var currentDate = new Date($("#hoursTimeLine").val());
        var series = [];
        var indexParam = $("#indexparam").find(".selected").data("name");

        data["startTime"] = dateFormat(dateAddSubtract(currentDate, -6));
        data["endTime"] = dateFormat(currentDate);

        data["deviceIdArr"] = [];
        data["deviceIdArr"].push($("#deviceId").val());
        data["type"] = indexParam;
        series = [{
            valueField: $("#deviceName").val(),
            name: $("#deviceName").val()
        }];

        $.ajax({
            url: "/partner/{tenant}/api/v1/serviceContrastNew".replace("{tenant}", getKeyByUrl()),
            type: "get",
            data: data,
            success: function (result) {
                var dataSource = [];
                //服务期限
                var subTitle = "(<spring:message code="label.tenant.create.period"/>：" + result.data.serviceState[0].start_date + "~" + result.data.serviceState[0].end_date + ")";
                if (result.result != "SUCCESS" || result.data.serviceData == null) {
                    createIndexServicesLineChart(dataSource, series, subTitle);
                    return;
                }

                var service = result.data.serviceData;
                for (var j = 0; j < service.length; j++) {
                    var copy = {};
                    if (dataSource.length == 0) {
                        copy["time"] = service[j]["date_id"];
                        copy[service[j]["deviceName"]] = service[j][indexParam];
                        dataSource.push(copy);
                    } else {
                        for (var i = 0; i < dataSource.length; i++) {
                            if (dataSource[i].time == service[j]["date_id"]) {
                                dataSource[i][service[j]["deviceName"]] = service[j][indexParam];
                                break;
                            } else if (i == (dataSource.length - 1)) {
                                copy["time"] = service[j]["date_id"];
                                copy[service[j]["deviceName"]] = service[j][indexParam];
                                dataSource.push(copy);
                                break;
                            }
                        }
                    }
                }
                createIndexServicesLineChart(dataSource, series, subTitle);
            },
            error: function (e) {
                console.log("e");
            }
        });

        hidePopup();
        $("#device_checkbox").find(".item-checked").removeClass("item-checked");
    }

    function showInfo(state, _this) {
        var message;
        if (state == 0) {
            message = '<spring:message code="label.happened.idle"/> ';
        } else if (state == 1) {
            message = '<spring:message code="label.normal.work"/>';
        } else if (state == -1) {
            message = '<spring:message code="label.plan.downtime"/>';
        }

        $(_this).append($('<div class="message-box message-box-change"></div>').attr("style","width:150px;").text(message).append($('<div class="triangle-border tb-border"></div><div class="triangle-border tb-background"></div>')));
    }

    function removeInfo(_this) {
        $(_this).children().remove();
    }

    function changePage(_this) {
        if ($(_this).hasClass("selector")) {
            return;
        }
        $("#mac").empty();
        $("dot").empty();
        $(".default").removeClass("selector");
        $(_this).addClass("selector");
        if ($(_this).data("id") == 'dot') {
            $("#mac").addClass("hidden");
            $("#dot-table").removeClass("hidden");
            $("#dot").removeClass("hidden");
            loadDotPage();
        } else {
            $("#dot-table").addClass("hidden");
            $("#dot").addClass("hidden");
            $("#mac").removeClass("hidden");
            loadMacPage();
        }
//        $("#" + $(_this).data("id")).removeClass("hidden");
    }

    function getDownTimeTable() {
        var table = $('#downTimeTable').DataTable({
            "dom": '<"datatable-header"<"dataTables_filter">l><"datatable-scroll"t><"datatable-footer dataTable-footer-padding"<"pull-left"i><"pull-right"p>>',
            paging: false,
            lengthChange: false,
            ordering: true,
            autoWidth: false,
            info: false,
            serverSide: false,
            fixedHeader: true,
            searching: false,
            aLengthMenu: [15],
            destroy: true,
            ajax: {
                url: '/partner/{tenant}/api/v1/downTimeLine'.replace("{tenant}", getKeyByUrl()),
                data: {
                    deviceId: $("#deviceId").val(),
                    time: $("#hoursTimeLine").val()
                },
                dataSrc: 'data'
            },
            columns: [
                {
                    data: 'repairStartTime'
                },
                {
                    data: 'repairEndTime'
                },
                {
                    data: 'faultMode'
                },
                {
                    data: 'reason'
                },
                {
                    data: 'repairPerson'
                }
            ],
            "language": {url: '/lang/datatable.chs.json'}
        });
    }

    function failureTimeLine() {
        $("#failureLine").html("");
        var $div = $("<div></div>").attr("style", "width:100%");
        for (var i = 0; i < 240; i++) {
            var $line = $("<div></div>").attr("data-timelinedata", i).attr("style", "background-color:#aaaa96;height:40px;position:relative;display:inline-block;width:" + 6 / 14.4 + "%");
            $div.append($line);
        }
        $("#failureLine").append($div);
        console.log(new Date());
        $.ajax({
            url: "/partner/{tenant}/api/v1/downTimeLineOfChart".replace("{tenant}", getKeyByUrl()),
            type: "get",
            data: {
                "time": $("#hoursTimeLine").val() + " 00:00:00",
                "deviceId": $("#deviceId").val()
            },
            success: function (data) {
                console.log(data);
                for (var i = 0; i < data.data.length; i++) {
                    var info = data.data[i];
                    console.log(info);
                    var zero = info.zero;
                    var fs = (info.failureStartTime - zero) / (1000 * 60 * 6);
                    var rs = (info.repairStartTime - zero) / (1000 * 60 * 6);
                    $("[data-timelinedata='" + fs.toFixed() + "']").append($('<div class="message-box message-box-change" onclick="updateIndex(this)" style="width: 260px;"></div>').text(info.failureInfo + " at " + new Date(info.failureStartTime).formatTime()).append($('<div class="triangle-border tb-border"></div><div class="triangle-border tb-background"></div>')));
                    $("[data-timelinedata='" + rs.toFixed() + "']").append($('<div class="message-box message-box-change" onclick="updateIndex(this)" style="width: 260px;"></div>').text(info.repairInfo + " at " + new Date(info.repairStartTime).formatTime()).append($('<div class="triangle-border tb-border"></div><div class="triangle-border tb-background"></div>')));
                    $("[data-timelinedata='" + fs.toFixed() + "']")[0].style['background-color'] = "#d7d7cd";
                    $("[data-timelinedata='" + rs.toFixed() + "']")[0].style['background-color'] = "#d7d7cd";
                }

            },
            error: function (e) {
                console.log(e);
            }
        })
    }

    function updateIndex(_this) {
        $(".message-box").attr("style", "z-index:888;width:260px;");
        $(_this).attr("style", "z-index:999;width:260px;");
    }

    function pieChartOfDownTimeWeek() {
        var data = {};
        var currentDate = new Date($("#hoursTimeLine").val());
        data["startTime"] = dateFormat(dateAddSubtract(currentDate, -6));
        data["endTime"] = dateFormat(currentDate);
        data["deviceId"] = ($("#deviceId").val());
        $.ajax({
            url: "/partner/{tenant}/api/v1/downTimePieOfChart".replace("{tenant}", getKeyByUrl()),
            type: "get",
            data: data,
            success: function (data) {
                showPieChart(data.data,'<spring:message code="label.fault"/>','<spring:message code="label.reason"/>','<spring:message code="label.reason.time"/>','<spring:message code="label.percent"/>','<spring:message code="label.total.time"/>');
                mttr=1;
                if (mtbr==1&&mttr==1){
                    $("#dot").addClass("hidden");
                }
            },
            error: function (e) {
                console.log(e)
            }
        })
    }

    function barChartOfDownTimeWeek() {
        var data = {};
        var currentDate = new Date($("#hoursTimeLine").val());
        data["startTime"] = dateFormat(dateAddSubtract(currentDate, -6));
        data["endTime"] = dateFormat(currentDate);
        data["deviceId"] = ($("#deviceId").val());
        $.ajax({
            url: "/partner/{tenant}/api/v1/downTimeBarOfChart".replace("{tenant}", getKeyByUrl()),
            type: "get",
            data: data,
            success: function (data) {
                showBarChart(data.data,'<spring:message code="label.show.day"/>');
                mtbr=1;
                if (mtbr==1&&mttr==1){
                    $("#dot").addClass("hidden");
                }
            },
            error: function (e) {
                console.log(e)
            }
        })
    }
</script>